//
//  UserMan.swift
//  whale
//
//  Created by topnet on 2022/3/29.
//

import UIKit


class UserMan: NSObject {
    static let shared = UserMan()
    private override init() {
        super.init()
        getUser()
    }
    
    var isLogin: Bool {
        if user != nil && user?.token != nil && user?.token != "" {
            return true
        }
        return false
    }
    var userObs = PublishSubject<UserModel>()
    
    
    func goLogin() {
        let vc: UIViewController
        if user == nil {
            vc = RegisterVC()
        }else {
            vc = LoginVC()
        }
        let nav = UINavigationController(rootViewController: vc)
        nav.modalPresentationStyle = .fullScreen
//        UIApplication.shared.currentVC?.navigationController?.pushViewController(vc, animated: true)
        UIApplication.shared.currentVC?.navigationController?.present(nav, animated: true)
    }
    
    
    var user: UserModel? {
        set{
            guard newValue != nil else {
                return
            }
            _user = newValue
            
            UserDefaults.standard.set(newValue!.toJSON().rawValue, forKey: KeysConfig.user)
            userObs.onNext(newValue!)
        }
            
        get{
            if _user == nil {
                getUser()
            }
            return _user
        }
    }

    private var _user: UserModel?
    
    private func getUser() {
        if let map = UserDefaults.standard.value(forKey: KeysConfig.user) as? [String: AnyHashable], !map.isEmpty {
            let json = JSON(map)
            user = UserModel(json: json)
            
        }
    }
    
    func logSuccess(_ user: UserModel) {
        self.user = user
//        PushMan.instance.setAlias(user.account ?? "")
    }
    
    func logOut() {
        user?.token = ""
        self.user = user
//        PushMan.instance.outAlias()
    }
}

///HY_2203278164
